﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;

namespace FisheryPlatform.Common
{
    public class IPAddressUtility : IPAddress
    {
        public IPAddressUtility(byte[] address)
            : base(address)
        {
        }

        /// <summary>
        /// 转换IP字符串到Long
        /// </summary>
        public static long ConvertToLong(string ipString)
        {
            #region

            if (Check(ipString) == false)
            {
                return 0;
            }
            string[] ipSegment = ipString.Split('.');
            for (int i = 0; i < ipSegment.Length; i++)
            {
                switch (ipSegment[i].Length)
                {
                    case 1:
                        ipSegment[i] = "00" + ipSegment[i]; break;
                    case 2:
                        ipSegment[i] = "0" + ipSegment[i]; break;
                }
            }
            return Convert.ToInt64(string.Join("", ipSegment));
            #endregion
        }

        /// <summary>
        /// 检查ip是否合法
        /// </summary>
        public static bool Check(string ipString)
        {
            #region
            IPAddress ipAddress;
            if (IPAddress.TryParse(ipString, out ipAddress))
            {
                return true;
            }
            return false;
            #endregion
        }

        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetClientIpFrom(HttpRequest request)
        {
            return string.IsNullOrEmpty(request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? request.UserHostAddress : request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        }
    }
}
